<template>
  <div class="app-page">
    <org-tree
      class="orgTree"
      title="组织机构"
      :tree-data="treeData01"
      :mouse-button="false"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange01"
    />
    <div class="content">
      <div>
        <el-table-form ref="form" class="merge-item">
          <el-form-item :table-form-merge="0.6">
            <el-select
              v-model="selectTimeRange"
              style="width: 120px;"
            >
              <el-option label="订气维度" value="1" />
              <el-option label="安检维度" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="最后订气时间:" :table-form-merge="1.6">
            <el-date-picker
              v-model="query.date"
              type="datetimerange"
              unlink-panels
              :clearable="selectTimeRange==='1'?false:true"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
          <el-form-item label="客户类型:">
            <el-select
              v-model="query.csmTypes"
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in customerTypeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户分类:" prop="csmItem">
            <el-select
              v-model="query.subType"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in subTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="销售员:">
            <el-select v-model="query.salesmanName" placeholder="请选择" filterable>
              <el-option label="请选择" value="" />
              <el-option
                v-for="item in SalesmanNameMap"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item>

          <el-form-item :table-form-merge="1.1">
            <el-input
              v-model="selectTimeDay"
              class="cus-input"
              placeholder="请输入"
              clearable
              :maxlength="4"
              :disabled="selectTimeRangeFlage"
            >
              <span slot="append"> 天未安检的客户</span>
            </el-input>
          </el-form-item>
          <template v-slot:btns>
            <el-button
              v-permission="5"
              type="primary"
              icon="el-icon-search"
              :loading="$loadingPlugin.fetchData"
              @click="search"
            >查询</el-button>
          </template>
        </el-table-form>
        <div style="margin-bottom: 10px;" class="btn-group">
          <el-button
            v-permission="6"
            type="primary"
            icon="el-icon-download"
            @click="batchExp"
          >导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        class="table"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        @fetch="fetchData"
      />
    </div>
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData01" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
  </div>
</template>

<script>
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import {
    selectUnCheckedAddress,
    organizationQueryList,
    userByOrgidQuery,
    queryExportDomain,
    uncheckedAddressExport,
    queryMap
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import OrgTree from '@/views/components/OrgTree'
  import dayjs from 'dayjs'

  export default {
    name: 'noCheckAddressSearch',
    components: {
      OrgTree, CsmDetail
    },
    data() {
      return {
        treeData01: [],
        currentOrg: null,
        exportDomain: '',
        currentGoodsType: null,
        SalesmanNameMap: [],
        calcTypeList: [],
        paymenFilList: [],
        customerTypeMap: [],
        subTypeList: [
          {
            label: '餐饮',
            value: 1
          },
          {
            label: '餐饮(个人)',
            value: 2
          },
          {
            label: '工厂',
            value: 3
          },
          {
            label: '机关事业单位',
            value: 4
          },
          {
            label: '部队',
            value: 5
          },
          {
            label: '居民(个人)',
            value: 6
          },
          {
            label: '学校',
            value: 7
          },
          {
            label: '其他商业',
            value: 8
          },
          {
            label: '餐饮(连锁)',
            value: 9
          },
          {
            label: '住宿业',
            value: 10
          },
          {
            label: '商贸服务业',
            value: 11
          },
          {
            label: '医疗卫生',
            value: 12
          },
          {
            label: '社会保障',
            value: 13
          }
        ],
        query: {
          salesmanName: '',
          subType: '',
          csmTypes: [1, 2],
          orgSNNo: '001000000000000000000',
          date: [dayjs().startOf('month'), dayjs().endOf('day')]
        },
        selectTimeRange: '1',
        selectTimeRangeFlage: true,
        selectTimeDay: '',
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              width: 30
            },
            { label: '责任机构', prop: 'nearStationName', width: 150 },
            {
              label: '客户类型',
              prop: 'csmType',
              width: 100,
              render: (h, { row }) => (
              <span>
                {row.csmType &&
                  formatColumnMap(
                    this.customerTypeMap,
                    'value',
                    row.csmType,
                    'desc'
                  )}
              </span>
            )
            },
            {
              label: '用户分类',
              prop: 'subType',
              width: 100,
              render: (h, { row }) => (
              <span>
                { row.subType ? formatColumnMap(this.subTypeList, 'value', row.subType, 'label') : '' }
              </span>
            )
            },
            {
              label: '客户编号',
              prop: 'csmCode',
              width: 100,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
            },
            { label: '客户名称', prop: 'csmName', width: 100 },
            { label: '客户地址', prop: 'csmRgAddress', width: 300 },
            { label: '联系电话', prop: 'csmRgPhone', minWidth: 110 },
            {
              label: '最后安检时间',
              prop: 'lastSCheckDt',
              minWidth: 160,
              render: (h, { row }) => (
              <span>
                {row.lastSCheckDt &&
                  parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            // { label: '销售员', prop: 'salesmanName', minWidth: 80 },
            {
              label: '最后订气时间',
              prop: 'lastBuyDt',
              width: 160,
              render: (h, { row }) => (
                <span>
                  {row.lastBuyDt &&
                    parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}')}
                </span>
              )
            }
            // { label: '配送员', prop: 'lastSender', width: 100 }
          ],
          data: []
        }
      }
    },
    watch: {
      selectTimeRange: function(val) {
        if (val === '1') {
          this.selectTimeRangeFlage = true
          this.selectTimeDay = ''
        } else {
          this.selectTimeRangeFlage = false
          this.selectTimeDay = 90
        }
      }
    },
    created() {
      this.getTreeData01()
      this.getExportDomain()
      this.queryOptionsMap()
    },
    methods: {
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        ])
        this.calcTypeList = res1.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res2.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.customerTypeMap = res3.data
      },
      async fetchData({ currentPage, pageSize }) {
        if (this.selectTimeRange === '2' && this.selectTimeDay === '') {
          this.$message({
            message: '请输入天数！',
            type: 'warning'
          })
          return
        }
        if (this.selectTimeRange === '1' && (!(this.query.date && this.query.date.length > 0))) {
          this.$message.warning('请选择最后订气时间！')
          return
        }
        const query = {
          json: { ...this._getQuery(this.query) },
          pageIndex: currentPage,
          pageSize
        }
        if (this.query.date && this.query.date.length > 0) {
          query.json.lastBuyDt = this.query.date[0]
          query.json.lastBuyDtEnd = this.query.date[1]
        }
        if (this.selectTimeRange === '2') {
          const nowDate = new Date()
          query.json.lastSCheckDt = new Date(
            nowDate.setDate(nowDate.getDate() - this.selectTimeDay)
          )
        }
        delete query.json.date
        const res = await selectUnCheckedAddress(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      getSalesmanName(orgId) {
        userByOrgidQuery({
          orgId: orgId,
          corpparm1: 0,
          utype: 64
        }).then(res => {
          this.SalesmanNameMap = res.data
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 获取组织机构数据
      async getTreeData01() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData01 = getTreeData(data)
      },
      // 选择组织机构变化
      currentChange01(current) {
        this.query.orgSNNo = current.orgSNNo
        this.getSalesmanName(current.orgId)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then(res => {
          console.log(res)
          this.exportDomain = res.data
        })
      },
      batchExp() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const currentPage = this.$refs.lbTable.currentPage
          const pageSize = this.$refs.lbTable.pageSize
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const query = {
            ...this._getQuery(this.query),
            currentPage,
            pageSize
          }
          if (this.selectTimeRange === '1' && (!(this.query.date && this.query.date.length > 0))) {
            this.$message.warning('请选择最后订气时间！')
            return
          }
          if (this.query.date && this.query.date.length > 0) {
            query.lastBuyDt = this.query.date[0]
            query.lastBuyDtEnd = this.query.date[1]
          }
          if (this.selectTimeRange === '2') {
            const nowDate = new Date()
            query.lastSCheckDt = new Date(
              nowDate.setDate(nowDate.getDate() - this.selectTimeDay)
            )
          }
          uncheckedAddressExport({
            paramInfo: query,
            kv: str // 表格列
          }).then(res => {
            window.open(
              `${this.exportDomain}/page/export/frame?key=${res.data}`,
              '_blank'
            )
          })
        })
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  padding: 0;
  .orgTree {
    height: 100%;
  }
  .content {
    width: 0;
    padding: 0 10px 0 10px;
    flex: 1;
    /deep/.cus-input {
      > .el-input__inner {
        width: 95px;
      }
    }
  }
  .form {
    margin-left: 10px;
  }
}

/deep/.el-select__tags {
  overflow: hidden;
  span {
    display: flex;
  }
}
.merge-item {
  /deep/.el-input .el-input-group__append:last-child {
    border: 1px solid #DCDFE6;
  }
}
</style>
